﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GameStateManagement
{
    public class Debris : DrawableObject //Microsoft.Xna.Framework.DrawableGameComponent
    {
        //public Matrix worldTransformMatrix;
        //protected float fScale;
        //protected Vector3 vWorldPosition;
        //protected Quaternion qRotation;
        //protected bool hasChanged;

        //protected Model actorModel;
        //protected ContentManager contentManager;
        //protected Matrix[] actorBones;
        protected Utils.Timer timers;

        //public BoundingSphere ModelBounds;
        //public BoundingSphere WorldBounds;

        public float fUpVel, fLeftVel;
        public float fMass;
        public float fRadius;


        //public bool followCam;

        public Debris(Game game)
            : base(game)
        {
            this.game = (GameStateManagementGame)game;
            timers = new Utils.Timer();
            worldTransformMatrix = Matrix.Identity;

            fRadius = 500.0f;
            fScale = 0.5f;
            vWorldPosition = new Vector3(fRadius, 0.0f, 0.0f);
            qRotation = Quaternion.Identity;
            hasChanged = false;

            followCam = true;

            fUpVel = 3.0f;
            fLeftVel = 2.0f;
            fMass = 30.0f;



        }

        public override void Initialize()
        {
            updateRotation();
            base.Initialize();

        }

        public float Scale
        {
            get { return fScale; }
            set
            {
                fScale = value;
                hasChanged = true;
            }
        }

        public Vector3 Position
        {
            get { return vWorldPosition; }
            set
            {
                vWorldPosition = value;
                hasChanged = true;
            }
        }

        public Quaternion Rotation
        {
            get { return qRotation; }
            set { qRotation = value; }
        }

        public void switchCam()
        {
            followCam = !followCam;
        }


        public void reflect()
        {
            this.fLeftVel = -this.fLeftVel;
            this.fUpVel = -this.fUpVel;
        }

        public Vector3 getVelocity()
        {
            return (this.worldTransformMatrix.Left * fLeftVel/fScale) + (this.worldTransformMatrix.Up * fUpVel/fScale);
        }

        public void setVelocity(Vector3 vel)
        {
            //vel *= 1.005f;
            float lscale = Vector3.Dot(vel, this.worldTransformMatrix.Left/fScale);
            float uscale = Vector3.Dot(vel, this.worldTransformMatrix.Up/fScale);

            this.fLeftVel = lscale;
            this.fUpVel = uscale;
        }

        /*public void updateWorldTransformMatrix()
        {
            hasChanged = false;

            Matrix scaleMatrix = Matrix.CreateScale(fScale);
            Matrix rotationMatrix = Matrix.CreateFromQuaternion(qRotation);
            Matrix translationMatrix = Matrix.CreateTranslation(vWorldPosition);

            worldTransformMatrix = scaleMatrix;
            worldTransformMatrix *= rotationMatrix;
            worldTransformMatrix *= translationMatrix;

            WorldBounds.Center = vWorldPosition;
            WorldBounds.Radius = ModelBounds.Radius * fScale * 0.85f;
        }*/

        public void updateRotation(){

            fRadius = this.Position.Length();

            float fyAngle = (float)Math.Acos(this.Position.Y / fRadius);
            float fzAngle = (float)Math.Asin(this.Position.X / Math.Sqrt(Math.Pow(this.Position.X, 2) + Math.Pow(this.Position.Z, 2)));
            if (this.Position.Z < 0)
            {
                fzAngle = (float)Math.PI - fzAngle;
            }

            Quaternion siderot = Quaternion.CreateFromAxisAngle(Vector3.UnitY, fzAngle);
            Quaternion uprot = Quaternion.CreateFromAxisAngle(-Vector3.UnitX, (float)(Math.PI / 2.0) - fyAngle);

            this.Rotation = siderot * uprot;

            updateWorldTransformMatrix();

        }


 
        public override void Update(GameTime gameTime)
        {
            Vector3 oldpos = this.Position;
            
            float dTime = ((float)gameTime.ElapsedGameTime.Ticks / System.TimeSpan.TicksPerMillisecond / 1000.0f);

            Vector3 left = this.worldTransformMatrix.Left;
            Vector3 newPos = this.Position + (this.worldTransformMatrix.Up/fScale * fUpVel);
            newPos.Normalize();
            newPos *= fRadius;
            this.Position = newPos;

            this.updateRotation();
            this.worldTransformMatrix.Left = left;
            this.worldTransformMatrix.Up = Vector3.Cross(this.worldTransformMatrix.Forward, this.worldTransformMatrix.Left) / fScale;

            
            Vector3 up = this.worldTransformMatrix.Up;
            newPos = this.Position + (this.worldTransformMatrix.Left/fScale * fLeftVel);
            newPos.Normalize();
            newPos *= fRadius;
            this.Position = newPos;

            this.updateRotation();

            this.worldTransformMatrix.Up = up;
            this.worldTransformMatrix.Left = -Vector3.Cross(this.worldTransformMatrix.Forward, this.worldTransformMatrix.Up) / fScale;

            //vel = this.Position - oldpos;
            
            timers.Update(gameTime);
            base.Update(gameTime);
        }

        protected override void LoadContent()
        {
            contentManager = new ContentManager(Game.Services, "Content");
            actorModel = contentManager.Load<Model>("Asteroid");
            actorBones = new Matrix[actorModel.Bones.Count];;
            celShader = contentManager.Load<Effect>("CelShader");
            texture = contentManager.Load<Texture2D>("bubblegum");
            celShader.Parameters["Texture"].SetValue(texture);
            celShader.Parameters["textureEnabled"].SetValue(true);
            changeEffectUsedByModel(actorModel, celShader);


            base.LoadContent();

            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                ModelBounds = BoundingSphere.CreateMerged(ModelBounds,
                mesh.BoundingSphere);
            }

        }

        protected override void UnloadContent()
        {
            contentManager.Unload();
            base.UnloadContent();
        }

        /*public override void Draw(GameTime gameTime)
        {
            if (hasChanged)
            {
                updateWorldTransformMatrix();
            }

            GraphicsDevice.RenderState.DepthBufferEnable = true;
            actorModel.CopyAbsoluteBoneTransformsTo(actorBones);
            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World =
                    actorBones[mesh.ParentBone.Index] * worldTransformMatrix;
                    if (followCam)
                    {
                        effect.View = GameplayScreen.camera.View;
                        effect.Projection = GameplayScreen.camera.Projection;
                    }
                    else
                    {
                        effect.View = GameplayScreen.CameraMatrix;
                        effect.Projection = GameplayScreen.ProjectionMatrix;
                    }
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;
                    effect.AmbientLightColor = GameplayScreen.ambientLightColor;
                    effect.DirectionalLight0.DiffuseColor = GameplayScreen.diffuseColor;
                    effect.DirectionalLight0.Direction = GameplayScreen.diffuseDirection;
                    effect.SpecularColor = GameplayScreen.specularColor;
                    effect.SpecularPower = GameplayScreen.specularPower;

                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }*/


    }
}
